package 数组;

import java.util.jar.Pack200;

/**
 * @Author Weton Li
 * @Date 2021/4/16 16:27
 */
public class 搜索插入位置 {

    public static int method(int[] nums, int target) {
        int n = nums.length;
        int l = 0;
        int r = n - 1;

        while (l < r) {
            int mid = (l + r) / 2;
            if (target > nums[mid]) {
                while (target > nums[++mid]) {
                    ++mid;
                    if (mid == n - 1) {
                        return n;
                    } else {
                        return mid;
                    }
                }
                l = mid + 1;
            } else if (target < nums[mid]) {
                if (target > nums[mid - 1]) {
                    return mid;
                }
                r = mid - 1;
            } else {
                return mid;
            }
        }
        return -1;
    }

    public static int method1(int[] nums, int target) {

        int left = 0, right = nums.length;

        while (left < right) {
            int mid = left + (right - left) / 2;

            if (nums[mid] >= target) {
                right = mid;
            } else {
                left = mid + 1;
            }
        }

        return left;
    }


    public static int method2(int[] nums, int target) {
        int left = 0, right = nums.length - 1;

        while (left <= right) {
            int mid = (left + right) / 2;
            if (nums[mid] < target) {
                left = mid + 1;
            } else if (nums[mid] > target) {
                right = mid - 1;
            }else {
                return mid;
            }
        }
        return left;
    }

    public static void main(String[] args) {
        int[] input = {1, 3, 5, 7};
        System.out.println(method1(input, 4)); // 2
        System.out.println(method1(input, 6)); // 3
        System.out.println(method1(input, 8)); // 4
    }
}
